/*
 * 地址选择
 */
'use strict';
import React, { Component } from 'react';
import {
    StyleSheet,
    Text,
    View,
    TouchableHighlight,
    Image,
    PixelRatio,
    ScrollView,
    AsyncStorage,
    Platform,
    TouchableOpacity,
    TextInput,
} from 'react-native';

import {Uploader} from 'rn-weui';


import Toast from 'antd-mobile/lib/toast';
import List from 'antd-mobile/lib/list';
import Picker from 'antd-mobile/lib/picker';
import InputItem from 'antd-mobile/lib/input-item';
import TextareaItem from 'antd-mobile/lib/textarea-item';
import ActivityIndicator from 'antd-mobile/lib/activity-indicator';
import Checkbox from 'antd-mobile/lib/checkbox';

import NavTitle from '../component/NavTitle';

var ImagePicker = require('react-native-image-picker');

import { createForm } from 'rc-form';

import XFetch from '../XFetch';

const CheckboxItem = Checkbox.CheckboxItem;

import CheckBox from '../utils/Checkbox';

import * as WechatAPI from 'react-native-wx';

Array.prototype.removeByValue = function(val) {
    for(var i=0; i<this.length; i++) {
        if(this[i] == val) {
            this.splice(i, 1);
            break;
        }
    }
}

class Authentication extends Component {
    constructor(props) {
        super(props);

        this.state = {
            files: [],
            productImgs:[],
            rzType:[],
            checked1:false,
            checked2:false,
            checked3:false
        }
    }

    componentDidMount(){

    }

    async _pay(){
        var Token = await AsyncStorage
            .getItem('Token')
            .then(function(value){
                return Promise.resolve(value);
            }).catch(function(error){
                return Promise.reject(error);
            });
        fetch(`http://www.weiweigo.com/app/content.aspx?method=pay&type=2`,{
            method:'GET',
            headers:{
                Authorization:Token,
            }
        }).then(data=>{
            data.json().then(data=>{
                if(data){
                    WechatAPI.pay({
                        partnerId: String(data.partnerid),
                        prepayId: String(data.prepayid),
                        nonceStr: String(data.noncestr),
                        timeStamp: String(data.timestamp),
                        package: String(data.package),
                        sign: String(data.sign),
                    }).then(data=>{
                        Toast.success('支付成功',2);
                        this.props.navigator.pop();
                    },error=>{
                        Toast.hide();
                        Toast.fail('支付异常',2);
                        this.props.navigator.pop();
                    })
                }
            })
        });
    }

    _editPwd(){
        if(this.state.rzType.length === 0){
            Toast.fail('必须选择类型', 1);
            return;
        }
        this.props.form.validateFields((error, value) => {
            if(!error){
                Toast.loading('加载中',100);
                let imgUrl = [];
                for(let ele of this.state.productImgs){
                    this._uploadImg(ele,imgUrl,2);
                }
                this._timer = setInterval(function(){
                    if(imgUrl.length === this.state.productImgs.length){
                        clearInterval(this._timer);
                        XFetch(`http://www.weiweigo.com/app/member.aspx?method=rzShengqing`,{
                            method:'POST',
                            body:JSON.stringify({
                                ...value,
                                rzType:this.state.rzType.join(','),
                                imgUrl:imgUrl.map(ele=>{
                                    return {
                                        src:ele
                                    }
                                }),
                            })
                        }).then(data=>{
                            if(data){
                                //console.log(data);
                                //Toast.success(data, 1);
                                //this.setState({
                                //    animating:false
                                //})
                                //this.props.navigator.pop();Toast.hide();
                                Toast.hide();
                                this._pay();
                            }
                        });
                    }
                }.bind(this),1000);

            }
        });
    }

    _uploadImg(img,obj,c) {
        let myHeaders = new Headers();
        myHeaders.append('Content-Type', 'multipart/form-data');

        let formData = new FormData();

        formData.append('imgFile', {uri: img.uri, name: img.fileName, type: 'image/jpeg'});
        formData.append('c', c);

        fetch(`http://www.weiweigo.com/app/member.aspx?method=upImg`,{
            method: 'POST',
            headers:myHeaders,
            body: formData,
        })
            .then(res => {
                res.json().then(data=>{
                    if(data.success){
                        if(Object.prototype.toString.call(obj) === '[object Array]'){
                            obj.push(data.val)
                        }else{
                            obj.focusimg=data.val;
                        }
                    }else{
                        this.setState({
                            animating:false
                        });
                        clearInterval(this._timer);
                    }
                });
            })
    }

    _selectProductImgs(){
        let options = {
            title: '',
            cancelButtonTitle:'取消',
            takePhotoButtonTitle:'拍照',
            chooseFromLibraryButtonTitle:'相册选择',
            mediaType:'photo',
            quality: 0.5
        };
        ImagePicker.showImagePicker(options, (response) => {
            let source = null;

            if(response.didCancel){
                return;
            }

            if(Platform.OS === 'ios') {
                // uri (on iOS)
                source = {uri: response.uri.replace('file://', ''), isStatic: true,fileName:response.fileName};
            } else {
                // uri (on android)
                source = {uri: response.uri, isStatic: true, fileName:response.fileName};
            }

            this.setState({
                productImgs: [...this.state.productImgs, source],
            })
        });
    }

    _renderImgs(){
        return this.state.productImgs.map((ele, index) => {
            return(
                <TouchableOpacity
                    key = {index}
                    onPress={() => this._showImage(index)}>
                    <Image style={[styles.showImage,{marginRight:5}]} source={ele}/>
                    <TouchableHighlight
                        style={styles.remove}
                        underlayColor='#c8c7cc'
                        onPress={() => this._removeImg(index)}>
                        <Text style={{fontSize:10,color:'#fff'}}>X</Text>
                    </TouchableHighlight>
                </TouchableOpacity>
            );
        });
    }

    _removeImg(index){
        this.state.productImgs.splice(index,1);
        this.setState({
            productImgs:this.state.productImgs
        });
    }

    render() {
        const { getFieldProps } = this.props.form;
        const data = [
            { value: '1', label: '服务' },
            { value: '2', label: '店铺' },
        ];
        return (
            <View style={styles.container}>
                <NavTitle
                    title='资历认证'
                    leftButton = {true}
                    leftImg = {require('../imgs/left.png')}
                    leftText = {'返回'}
                    leftHander = {()=>{this.props.navigator.pop()}}
                    headColor = '#fbdc3a'
                />
                <View style={styles.content}>
                    <List renderHeader={() => '资历认证'}>
                        <TextareaItem
                            rows={5}
                            {...getFieldProps('summary',{
                                rules: [{required: true}],
                                initialValue:'企业认证是微微购针对普通会员推出的收费认证，只要你是一家企业，有营业执照，即可进行认证，您续费后，可以上传企业营业执照图片，国家审核的相关认证的资质图片，会在您公司店铺页面点亮认证标识，让您更好的获得买家信赖'

                            })}
                            placeholder="请输入资历认证"
                        />
                    </List>

                    {/*<Picker
                        data={[{
                            label: '商家',
                            value: '1',
                        },{
                            label: '服务',
                            value: '2',
                        },{
                            label: '商家和服务',
                            value: '1,2',
                        }]}
                        title="认证类型"
                        {...getFieldProps('rzType',{
                            rules: [{required: true}],
                        })}
                        cols={1}
                    >
                        <List.Item arrow="horizontal">认证类型</List.Item>
                    </Picker>*/}

                    {/* <List renderHeader={() => '认证类型'}>
                        {data.map(i => (
                            <CheckboxItem
                                key={i.value}
                                onChange={(value)=>{
                                    if(value.target.checked){
                                        this.setState({
                                            rzType:[...this.state.rzType,i.value]
                                        })
                                    }else{
                                        this.state.rzType.removeByValue(i.value);
                                        this.setState({
                                            rzType:this.state.rzType
                                        })
                                    }
                                }}
                            >
                                {i.label}
                            </CheckboxItem>
                        ))}
                    </List>*/}

                    <View style={{flexDirection:'row',marginTop:10,paddingLeft:10,alignItems:'center'}}>
                        <Text style={{color:'#333',marginRight:10}}>认证类型:</Text>
                        <CheckBox
                            label='店铺'
                            checkboxStyle = {{width:16,height:16}}
                            checked={this.state.checked1}
                            underlayColor="rgba(0,0,0,0)"
                            onChange={(checked) => {
                                if(!checked){
                                        this.setState({
                                            checked1:!this.state.checked1,
                                            rzType:[...this.state.rzType,1]
                                        })
                                }else{
                                    this.state.rzType.removeByValue(1);
                                    this.setState({
                                        checked1:!this.state.checked1,
                                        rzType:this.state.rzType
                                    })
                                }
                            }}
                        />
                        <CheckBox
                            label='服务'
                            checkboxStyle = {{width:16,height:16}}
                            checked={this.state.checked2}
                            underlayColor="rgba(0,0,0,0)"
                            onChange={(checked) => {
                                if(!checked){
                                    this.setState({
                                        checked2:!this.state.checked2,
                                        rzType:[...this.state.rzType,2]
                                    })
                                }else{
                                    this.state.rzType.removeByValue(2);
                                    this.setState({
                                        checked2:!this.state.checked2,
                                        rzType:this.state.rzType
                                    })
                                }
                            }}
                        />
                        <CheckBox
                            label='365/年'
                            checkboxStyle = {{width:16,height:16}}
                            checked={this.state.checked3}
                            underlayColor="rgba(0,0,0,0)"
                            onChange={(checked) => {
                                if(!checked){
                                    this.setState({
                                        checked3:!this.state.checked3,
                                        //rzType:[...this.state.rzType,3]
                                    })
                                }else{
                                    //this.state.rzType.removeByValue(3);
                                    this.setState({
                                        checked3:!this.state.checked3,
                                        //rzType:this.state.rzType
                                    })
                                }
                            }}
                        />
                    </View>
                    <View style={{backgroundColor:"#FFF",marginTop:10}}>
                        <ScrollView horizontal={true} contentContainerStyle={[styles.proHead]} showsHorizontalScrollIndicator={false}>
                            {
                                this._renderImgs()
                            }
                            <TouchableOpacity style={styles.proBtn} onPress={this._selectProductImgs.bind(this)}>
                                <Text style={[styles.proTxt,{fontSize:48,marginBottom:3}]}>+</Text>
                            </TouchableOpacity>
                        </ScrollView>
                    </View>

                    <TouchableHighlight
                        style={styles.loginBtn}
                        onPress={this._editPwd.bind(this)}
                    >
                        <Text style={styles.loginText}>确定</Text>
                    </TouchableHighlight>

                    </View>

                </View>
        )
    }

}

const styles = StyleSheet.create({
    container: {
        backgroundColor: '#EEEEEF',
        flex: 1,
    },
    head:{
        flexDirection:'row',
        alignItems:'center'
    },
    eye:{
        width:25,
        height:20
    },
    text:{
        fontSize:14,
        color:'#333',
        marginLeft:5
    },
    itemStyle:{
        flexDirection:'row'
    },
    keys:{
        marginRight:10,
    },
    content:{
        padding:10,
        paddingLeft:0,
        paddingRight:0
    },
    telInput:{
        padding:5,
        paddingLeft:10,
        height:200,
        fontSize:16,
        flex:1
    },
    btnInput:{
        borderWidth:1/PixelRatio.get(),
        marginTop:20,
        borderRadius:4,
        borderColor:'#CCC',
        flexDirection:'row',
        backgroundColor:'#FFF',
        marginBottom:20
    },
    loginBtn:{
        padding:15,
        backgroundColor:'#FBDC3A',
        marginTop:20,
        borderRadius:3,
        justifyContent:'center',
        alignItems:'center'
    },
    loginText:{
        fontSize:16
    },
    proHead:{
        flexDirection:'row',
        alignItems:'center',
        padding:5,
        flex:1,
        backgroundColor:"#FFF",
        justifyContent:'center',
    },
    proBtn:{
        alignItems:'center',
        justifyContent:'center',
        borderWidth:1,
        padding:10,
        borderColor:'#D1D1D1',
        paddingLeft:25,
        paddingRight:25
    },
    proTxt:{
        fontSize:13,
        color:'#666'
    },
    logoImg:{
        width:80,
        height:80,
        marginRight:5
    },
    showImage:{
        width:80,
        height:80
    },
    remove:{
        position: 'absolute',
        top: -4,
        right: 3,
        width: 16,
        height: 16,
        borderRadius: 8,
        backgroundColor: '#000',
        alignItems:'center',
        justifyContent:'center'
    }
});

export default createForm()(Authentication);
